package com.buster.dumbshellarts;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {

	// private Context mycontext;
	// The Android's default system path of your application database.
	private static String DB_PATH = "/data/data/com.buster.dumbshellarts/databases/";
	/*
	 * private String DB_PATH = "/data/data/" +
	 * mycontext.getApplicationContext().getPackageName() + "/databases/";
	 */
	private static String DB_NAME = "moviesdb.jpg";
	private static String DB_TABLE = "Movies";

	private SQLiteDatabase myDataBase;

	private final Context myContext;

	public static final String COL_TITLE = "Title";
	public static final String COL_DIRECTOR = "Director";
	public static final String COL_ACTORS = "Actors";
	public static final String COL_YEAR = "Year";
	public static final String COL_URL = "URL";
	public static final String COL_LANGUAGE = "Language";
	public static final String COL_ID = "_id";

	/**
	 * Constructor Takes and keeps a reference of the passed context in order to
	 * access to the application assets and resources.
	 * 
	 * @param context
	 */
	public DBHelper(Context context) {

		super(context, DB_NAME, null, 1);
		this.myContext = context;
	}

	/**
	 * Creates a empty database on the system and rewrites it with your own
	 * database.
	 * */
	public void createDataBase() throws IOException {

		boolean dbExist = checkDataBase();

		if (dbExist) {
			// do nothing - database already exist
		} else {

			// By calling this method and empty database will be created into
			// the default system path
			// of your application so we are gonna be able to overwrite that
			// database with our database.
			this.getReadableDatabase();

			try {

				copyDataBase();

			} catch (IOException e) {

				throw new Error("Error copying database");

			}
		}

	}

	/**
	 * Check if the database already exist to avoid re-copying the file each
	 * time you open the application.
	 * 
	 * @return true if it exists, false if it doesn't
	 */
	private boolean checkDataBase() {

		SQLiteDatabase checkDB = null;

		try {
			String myPath = DB_PATH + DB_NAME;
			checkDB = SQLiteDatabase.openDatabase(myPath, null,
					SQLiteDatabase.OPEN_READONLY);

		} catch (SQLiteException e) {

			// database does't exist yet.

		}

		if (checkDB != null) {

			checkDB.close();

		}

		return checkDB != null ? true : false;
	}

	/**
	 * Copies your database from your local assets-folder to the just created
	 * empty database in the system folder, from where it can be accessed and
	 * handled. This is done by transfering bytestream.
	 * */
	private void copyDataBase() throws IOException {

		// Open your local db as the input stream
		InputStream myInput = myContext.getAssets().open(DB_NAME);

		// Path to the just created empty db
		String outFileName = DB_PATH + DB_NAME;

		// Open the empty db as the output stream
		OutputStream myOutput = new FileOutputStream(outFileName);

		// transfer bytes from the inputfile to the outputfile
		byte[] buffer = new byte[1024];
		int length;
		while ((length = myInput.read(buffer)) > 0) {
			myOutput.write(buffer, 0, length);
		}

		// Close the streams
		myOutput.flush();
		myOutput.close();
		myInput.close();

	}

	public boolean isDataBaseOpen() {
		return myDataBase.isOpen();
	}

	public void openDataBase() throws SQLException {

		// Open the database
		String myPath = DB_PATH + DB_NAME;
		myDataBase = SQLiteDatabase.openDatabase(myPath, null,
				SQLiteDatabase.OPEN_READONLY);

	}

	@Override
	public synchronized void close() {

		if (myDataBase != null)
			myDataBase.close();

		super.close();

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

	@Override
	public void onCreate(SQLiteDatabase db) {

	}

	// Add your public helper methods to access and get content from the
	// database.
	// You could return cursors by doing "return myDataBase.query(....)" so it'd
	// be easy
	// to you to create adapters for your views.

	public long createMovie(String title, String director, String cast,
			int year, String URL, int language) {
		ContentValues v = new ContentValues();
		v.put(COL_TITLE, title);
		v.put(COL_DIRECTOR, director);
		v.put(COL_ACTORS, cast);
		v.put(COL_YEAR, year);
		v.put(COL_URL, URL);
		v.put(COL_LANGUAGE, language);

		return myDataBase.insert(DB_TABLE, null, v);
	}

	public boolean deleteMovie(long id) {
		return myDataBase.delete(DB_TABLE, COL_ID + "=" + id, null) > 0;
	}

	public boolean deleteAllMovies() {
		return myDataBase.delete(DB_TABLE, null, null) > 0;
	}

	public Cursor getAllMovies() {
		return myDataBase.query(DB_TABLE, new String[] { COL_ID, COL_TITLE,
				COL_DIRECTOR, COL_ACTORS, COL_YEAR, COL_URL, COL_LANGUAGE },
				null, null, null, null, null);
	}

	public Cursor getMovie(long id) {
		Cursor mCursor = myDataBase
				.query(true, DB_TABLE, new String[] { COL_ID, COL_TITLE,
						COL_DIRECTOR, COL_ACTORS, COL_YEAR, COL_URL,
						COL_LANGUAGE }, COL_ID + "=" + id, null, null, null,
						null, null);

		if (mCursor != null)
			mCursor.moveToFirst();
		return mCursor;
	}

	public Cursor getRandomMovie() {
		Cursor mrCursor = myDataBase.query(DB_TABLE, new String[] { COL_ID,
				COL_TITLE, COL_DIRECTOR, COL_ACTORS, COL_YEAR, COL_URL,
				COL_LANGUAGE }, null, null, null, null, "RANDOM() LIMIT 1");

		if (mrCursor != null)
			mrCursor.moveToFirst();
		return mrCursor;
	}

	public Cursor getRandomMovieByLanguage(int language) {
		Cursor mCursor = myDataBase.query(DB_TABLE, new String[] { COL_ID,
				COL_TITLE, COL_DIRECTOR, COL_ACTORS, COL_YEAR, COL_URL,
				COL_LANGUAGE }, COL_LANGUAGE + "=" + language, null, null,
				null, "RANDOM() LIMIT 1");

		if (mCursor != null)
			mCursor.moveToFirst();
		return mCursor;
	}

	public Cursor getRandomMovieByDecades(boolean s1930, boolean s1940,
			boolean s1950, boolean s1960, boolean s1970, boolean s1980,
			boolean s1990, boolean s2000, boolean s2010) {
		String str = COL_LANGUAGE + " IN (1,2,3,4,5,6) AND ((";
		str = str
				+ this.getDecadesSQL(s1930, s1940, s1950, s1960, s1970, s1980,
						s1990, s2000, s2010);

		Cursor mrCursor = myDataBase.query(DB_TABLE, new String[] { COL_ID,
				COL_TITLE, COL_DIRECTOR, COL_ACTORS, COL_YEAR, COL_URL,
				COL_LANGUAGE }, str, null, null, null, "RANDOM() LIMIT 1");

		if (mrCursor != null)
			mrCursor.moveToFirst();
		return mrCursor;
	}

	public String getDecadesSQL(boolean s1930, boolean s1940, boolean s1950,
			boolean s1960, boolean s1970, boolean s1980, boolean s1990,
			boolean s2000, boolean s2010) {
		String str = "";
		boolean orCreated = false;
		if (s1930) {
			str = str + COL_YEAR + ">= 1930 AND " + COL_YEAR + "< 1940)";
			orCreated = true;
		}
		if (s1940) {
			if (orCreated)
				str = str + "OR (" + COL_YEAR + ">= 1940 AND " + COL_YEAR
						+ "< 1950)";
			else {
				str = str + COL_YEAR + ">= 1940 AND " + COL_YEAR + "< 1950)";
				orCreated = true;
			}
		}
		if (s1950) {
			if (orCreated)
				str = str + "OR (" + COL_YEAR + ">= 1950 AND " + COL_YEAR
						+ "< 1960)";
			else {
				str = str + COL_YEAR + ">= 1950 AND " + COL_YEAR + "< 1960)";
				orCreated = true;
			}
		}
		if (s1960) {
			if (orCreated)
				str = str + "OR (" + COL_YEAR + ">= 1960 AND " + COL_YEAR
						+ "< 1970)";
			else {
				str = str + COL_YEAR + ">= 1960 AND " + COL_YEAR + "< 1970)";
				orCreated = true;
			}
		}
		if (s1970) {
			if (orCreated)
				str = str + "OR (" + COL_YEAR + ">= 1970 AND " + COL_YEAR
						+ "< 1980)";
			else {
				str = str + COL_YEAR + ">= 1970 AND " + COL_YEAR + "< 1980)";
				orCreated = true;
			}
		}
		if (s1980) {
			if (orCreated)
				str = str + "OR (" + COL_YEAR + ">= 1980 AND " + COL_YEAR
						+ "< 1990)";
			else {
				str = str + COL_YEAR + ">= 1980 AND " + COL_YEAR + "< 1990)";
				orCreated = true;
			}
		}
		if (s1990) {
			if (orCreated)
				str = str + "OR (" + COL_YEAR + ">= 1990 AND " + COL_YEAR
						+ "< 2000)";
			else {
				str = str + COL_YEAR + ">= 1990 AND " + COL_YEAR + "< 2000)";
			}
		}
		if (s2000) {
			if (orCreated)
				str = str + "OR (" + COL_YEAR + ">= 2000 AND " + COL_YEAR
						+ "< 2010)";
			else {
				str = str + COL_YEAR + ">= 2000 AND " + COL_YEAR + "< 2010)";
				orCreated = true;
			}
		}
		if (s2010) {
			if (orCreated)
				str = str + "OR (" + COL_YEAR + ">= 2010 AND " + COL_YEAR
						+ "< 2020)";
			else {
				str = str + COL_YEAR + ">= 2010 AND " + COL_YEAR + "< 2020)";
			}
		}

		str = str + ")";
		return str;
	}

	public Cursor getRandomMovieByLanguageAndDecades(int language,
			boolean s1930, boolean s1940, boolean s1950, boolean s1960,
			boolean s1970, boolean s1980, boolean s1990, boolean s2000,
			boolean s2010) {

		String str = COL_LANGUAGE + "=" + language + " AND ((";

		str = str
				+ this.getDecadesSQL(s1930, s1940, s1950, s1960, s1970, s1980,
						s1990, s2000, s2010);

		Cursor mCursor = myDataBase.query(DB_TABLE, new String[] { COL_ID,
				COL_TITLE, COL_DIRECTOR, COL_ACTORS, COL_YEAR, COL_URL,
				COL_LANGUAGE }, str, null, null, null, "RANDOM() LIMIT 1");

		if (mCursor != null)
			mCursor.moveToFirst();
		return mCursor;
	}

	public boolean updateMovie(long id, String title, String director,
			String cast, int year, String URL, int language, String lastUsed) {
		ContentValues v = new ContentValues();
		v.put(COL_TITLE, title);
		v.put(COL_DIRECTOR, director);
		v.put(COL_ACTORS, cast);
		v.put(COL_YEAR, year);
		v.put(COL_URL, URL);
		v.put(COL_LANGUAGE, language);

		return myDataBase.update(DB_TABLE, v, COL_ID + "=" + id, null) > 0;
	}

}